package com.xja.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xja.model.entity.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @author 蔡建国
 * Date  2025/6/11 22:41
 */
@Configuration
@RequiredArgsConstructor
public class AppConfig {

    private final VectorStore vectorStore;

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void fillMySqlByVectorStore() {
        // 查询所有文档
        List<Document> documentList = vectorStore.similaritySearch(SearchRequest.builder()
                .similarityThresholdAll()
                .topK(16384)
                .build());
        if (CollUtil.isEmpty(documentList)) {
            return;
        }
        List<Collection> collectionList = documentList.stream()
                .map(d -> new Collection(d.getId(), d.getText()))
                .toList();
        // 同步到mysql
        Db.saveOrUpdateBatch(collectionList);
    }
}